<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="代理商名称">
              <a-select
                v-model="queryParam.agentId"
                placeholder="请选择代理商"
                showSearch
                :filterOption="filterOption"
                allowClear
              >
                <a-select-option v-for="item in agentList" :key="item.id">{{ item.corporateName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="addVisible = true" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('代理商每月收益')">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down"/></a-button>
      </a-dropdown>
    </div>

    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <span slot="fileName" slot-scope="text, record">
          <a slot="fileName" :href="record.url" target="_blank">{{ text }}</a>
        </span>

        <span slot="action" slot-scope="text, record">
          <a @click="openEditModal(record)">编辑</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a style="color: red;">删除</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>

    <a-modal
      :visible="addVisible"
      :width="1200"
      title="新增代理商每月收益"
      :confirmLoading="submitLoad"
      destroyOnClose
      @cancel="handleAddCancel"
      @ok="handleAddSubmit"
    >
      <a-spin :spinning="spinning">
        <a-form-model ref="ruleForm" v-for="(item, index) in addFormDataList" :key="index" :model="item">
          <a-row>
            <a-col :span="20">
              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="代理商名称"
                    prop="agentId"
                    :labelCol="{ span: 8 }"
                    :wrapperCol="{ span: 14, offset: 1 }"
                    labelInValue
                    :rules="{
                      required: true,
                      message: '请选择代理商',
                      trigget: 'change'
                    }"
                  >
                    <a-select v-model="item.agentId"  placeholder="请选择代理商" showSearch :filterOption="filterOption">
                      <a-select-option v-for="item in agentList" :key="item.id">{{ item.corporateName }}</a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="结算年月"
                    prop="years"
                    :labelCol="{ span: 8 }"
                    :wrapperCol="{ span: 14, offset: 1 }"
                    :rules="[
                      {
                        required: true,
                        message: '请选择结算年月',
                        trigget: 'change'
                      }
                    ]"
                  >
                    <a-month-picker
                      style="width: 100%;"
                      v-model="item.years"
                      placeholder="请选择结算年月"
                      valueFormat="YYYY-MM"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="当月电量"
                    prop="quantity"
                    :labelCol="{ span: 8 }"
                    :wrapperCol="{ span: 14, offset: 1 }"
                    :rules="[
                      {
                        required: true,
                        message: '请输入当月电量',
                        trigget: 'change'
                      }
                    ]"
                  >
                    <a-input v-model="item.quantity" placeholder="请输入当月电量" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="交易户数"
                    prop="transaction"
                    :labelCol="{ span: 8 }"
                    :wrapperCol="{ span: 14, offset: 1 }"
                    :rules="[
                      {
                        required: true,
                        type: 'number',
                        message: '请输入交易户数',
                        trigget: 'change'
                      }
                    ]"
                  >
                    <a-input-number v-model="item.transaction" placeholder="请输入交易户数" style="width: 100%;" />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="图片"
                    prop="fileList"
                    :labelCol="{ span: 8 }"
                    :wrapperCol="{ span: 14, offset: 1 }"
                    :rules="[
                      {
                        required: true,
                        type: 'array',
                        message: '请上传图片',
                        trigget: 'change'
                      }
                    ]"
                  >
                    <a-upload
                      v-if="Array.isArray(item.fileList) && item.fileList.length === 0"
                      ref="uploadRef"
                      name="file"
                      :action="actionUrl"
                      :headers="{
                        'X-Access-Token': $store.state.user.token
                      }"
                      :remove="() => (item.fileList = [])"
                      :beforeUpload="beforeUpload"
                      @change="upChange(arguments[0], 'add', index)"
                      :showUploadList="false"
                    >
                      <a-button> <a-icon type="upload" /> 文件上传 </a-button>
                    </a-upload>
                    <div v-else style="display: flex;justify-content: space-between;align-items: center;">
                      <span class="preview" @click="preview(item.fileList[0]['syUrl'])">{{
                        item.fileList[0]['fileName']
                      }}</span>
                      <a-icon
                        type="delete"
                        :style="{ color: 'red' }"
                        style="cursor: pointer;"
                        @click="delFile('edit', index)"
                      />
                    </div>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-col>
            <a-col :span="4">
              <a-col :span="2" style="display: flex;align-items: center;">
                <a-form-model-item>
                  <a-button
                    type="link"
                    style="color: red;"
                    @click="delRowHandle(index)"
                    v-if="addFormDataList.length > 1"
                    >删除</a-button
                  >
                </a-form-model-item>
              </a-col>
            </a-col>
          </a-row>
        </a-form-model>
        <div style="text-align: center">
          <a-button type="link" @click="addRowHandle">+ 新增</a-button>
        </div>
      </a-spin>
    </a-modal>
    <a-modal
      :visible="editVisible"
      :width="500"
      title="编辑代理商每月收益"
      :confirmLoading="submitLoad"
      destroyOnClose
      @cancel="handleEditCancel"
      @ok="handleEditSubmit"
    >
      <a-spin :spinning="spinning">
        <a-form-model ref="editRuleForm" :model="formData">
          <a-row>
            <a-col :span="24">
              <a-form-model-item
                label="代理商名称"
                prop="agentId"
                :labelCol="{ span: 6 }"
                :wrapperCol="{ span: 18 }"
                labelInValue
                :rules="{
                  required: true,
                  message: '请选择代理商',
                  trigget: 'change'
                }"
              >
                <a-select v-model="formData.agentId" placeholder="请选择代理商" showSearch>
                  <a-select-option v-for="item in agentList" :key="item.id">{{ item.corporateName }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                label="结算年月"
                prop="years"
                :labelCol="{ span: 6 }"
                :wrapperCol="{ span: 18 }"
                :rules="[
                  {
                    required: true,
                    message: '请选择结算年月',
                    trigget: 'change'
                  }
                ]"
              >
                <a-month-picker
                  v-model="formData.years"
                  placeholder="请选择结算年月"
                  valueFormat="YYYY-MM"
                  style="width: 100%;"
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                label="当月电量"
                prop="quantity"
                :labelCol="{ span: 6 }"
                :wrapperCol="{ span: 18 }"
                :rules="[
                  {
                    required: true,
                    message: '请输入当月电量',
                    trigget: 'change'
                  }
                ]"
              >
                <a-input v-model="formData.quantity" placeholder="请输入当月电量" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                label="交易户数"
                prop="transaction"
                :labelCol="{ span: 6 }"
                :wrapperCol="{ span: 18 }"
                :rules="[
                  {
                    required: true,
                    type: 'number',
                    message: '请输入交易户数',
                    trigget: 'change'
                  }
                ]"
              >
                <a-input-number v-model="formData.transaction" style="width: 100%;" placeholder="请输入交易户数" />
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item
                label="图片"
                prop="fileList"
                :labelCol="{ span: 6 }"
                :wrapperCol="{ span: 18 }"
                :rules="[
                  {
                    required: true,
                    type: 'array',
                    message: '请上传图片',
                    trigget: 'change'
                  }
                ]"
              >
                <a-upload
                  v-if="Array.isArray(formData.fileList) && formData.fileList.length === 0"
                  ref="uploadRef"
                  name="file"
                  :action="actionUrl"
                  :headers="{
                    'X-Access-Token': $store.state.user.token
                  }"
                  :remove="() => (formData.fileList = [])"
                  :beforeUpload="beforeUpload"
                  @change="upChange(arguments[0], 'edit', index)"
                  :showUploadList="false"
                >
                  <a-button> <a-icon type="upload" /> 文件上传 </a-button>
                </a-upload>
                <div v-else style="display: flex;justify-content: space-between;align-items: center;">
                  <span class="preview" @click="preview(formData.fileList[0]['syUrl'])">{{
                    formData.fileList[0]['fileName']
                  }}</span>
                  <a-icon type="delete" :style="{ color: 'red' }" style="cursor: pointer;" @click="delFile('edit')" />
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </a-spin>
    </a-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { apiGetAgentList, apiAddAgentIncome, apiEditAgentIncome } from '@/api/contractManage/agentIncome'

export default {
  name: 'PolicyDoc',
  mixins: [JeecgListMixin, mixinDevice],
  data() {
    return {
      description: '政策文档管理',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '代理商名称',
          align: 'center',
          dataIndex: 'agentName'
        },
        {
          title: '申报电量',
          align: 'center',
          dataIndex: 'quantity'
        },
        {
          title: '结算年月',
          align: 'center',
          dataIndex: 'years'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/gzAgentIncome/list',
        delete: '/gzAgentIncome/delete',
        exportXlsUrl: '/gzAgentIncome/exportXls',
        deleteBatch: '/gzAgentIncome/deleteBatch'
      },
      curType: '',
      addVisible: false,
      modalTitle: '新增电量申报',
      submitLoad: false,
      addFormDataList: [
        {
          agentId: undefined,
          agentName: undefined,
          quantity: undefined,
          years: undefined,
          transaction: undefined,
          fileList: []
        }
      ],
      formData: {
        agentId: undefined,
        agentName: undefined,
        quantity: undefined,
        years: undefined,
        transaction: undefined,
        fileList: []
      },
      curRow: {},
      curRowType: 'add',
      agentList: [],
      editVisible: false,
      spinning: false
    }
  },
  created() {
    this.getAgentList()
  },
  computed: {
    actionUrl() {
      return process.env.VUE_APP_API_BASE_URL + '/api/file/upload'
    }
  },
  methods: {
    //获取代理商
    async getAgentList() {
      const { code, result } = await apiGetAgentList()
      if (code === 0) {
        this.agentList = result.records.map(item => {
          item.label = item.corporateName
          return item
        })
      }
    },
    // 上传前
    beforeUpload(file) {
      const { type, size } = file
      if (!type.includes('image/')) {
        this.$message.error('只能上传图片格式文件！')
        return Promise.reject()
      }
      if (10 * 1024 * 1024 < size) {
        this.$message.error('图片最大为10M！')
        return Promise.reject()
      }
      this.spinning = true
      return Promise.resolve(file)
    },
    // 文件上传
    upChange({ file }, type, index) {
      const { status, response } = file
      if (status === 'done') {
        const { code, result } = response
        this.spinning = false
        if (code === 0) {
          const { fileId, name: fileName, url } = result
          if (type === 'add') {
            this.addFormDataList[index].fileList = [
              {
                fileName,
                fileId,
                syUrl: url
              }
            ]
            this.$refs.ruleForm[index].validateField('fileList')
          } else {
            this.formData.fileList = [
              {
                fileName,
                fileId,
                syUrl: url
              }
            ]
            this.$refs.editRuleForm.validateField('fileList')
          }
        }
      }
    },
    delFile(type, index) {
      if (type === 'edit') {
        this.formData.fileList = []
      } else {
        this.addFormDataList[index]['fileList'] = []
      }
    },
    // 新增一列
    addRowHandle() {
      this.addFormDataList.push({
        agentId: undefined,
        agentName: undefined,
        quantity: undefined,
        years: undefined,
        transaction: undefined,
        fileList: []
      })
    },
    // 删除一列
    delRowHandle(index) {
      this.addFormDataList.splice(index, 1)
    },
    // 编辑
    openEditModal(row) {
      this.editVisible = true
      let params = Object.assign({}, row)
      if (row.fileId) {
        params.fileList = [
          {
            fileName: row.fileName,
            fileId: row.fileId,
            syUrl: row.syUrl
          }
        ]
      } else {
        params.fileList = []
      }
      this.formData = params
    },
    // 新增提交
    async handleAddSubmit() {
      let addFormRefList = this.$refs.ruleForm
      for (const item of addFormRefList) {
        await item.validate()
      }
      this.submitLoad = true
      this.addFormDataList = this.addFormDataList.map(item => {
        let data = this.agentList.find(itm => itm.id === item.agentId)
        item.agentName = data && data.corporateName
        const { fileId, fileName, syUrl } = item.fileList[0]
        item.fileName = fileName
        item.fileId = fileId
        item.syUrl = syUrl
        return item
      })
      const { code, message } = await apiAddAgentIncome(this.addFormDataList)
      this.submitLoad = false
      if (code === 200) {
        this.handleAddCancel()
        this.searchQuery()
        this.$message.success('操作成功！')
      } else {
        this.$message.success(message)
      }
    },
    handleAddCancel() {
      this.addVisible = false
      this.addFormDataList = [
        {
          agentId: undefined,
          agentName: undefined,
          quantity: undefined,
          years: undefined,
          transaction: undefined,
          fileList: []
        }
      ]
    },
    // 编辑提交
    async handleEditSubmit() {
      await this.$refs.editRuleForm.validate()
      this.submitLoad = true
      this.formData.agentName = this.agentList.find(itm => itm.id === this.formData.agentId).corporateName
      const { code, message } = await apiEditAgentIncome(Object.assign({}, this.formData, this.formData.fileList[0]))
      this.submitLoad = false
      if (code === 200) {
        this.handleEditCancel()
        this.searchQuery()
        this.$message.success('操作成功！')
      } else {
        this.$message.success(message)
      }
    },
    // 取消编辑
    handleEditCancel() {
      this.formData = {
        name: undefined,
        agentId: undefined,
        number: undefined,
        remarks: undefined,
        transaction: undefined,
        fileList: []
      }
      this.$refs.editRuleForm.resetFields()
      this.editVisible = false
    },
    del() {
      this.formData.fileList = []
    },
    filterOption(value, option) {
      return option.componentOptions.children[0].text.indexOf(value) >= 0
    },
    preview(url) {
      console.log(url, 'url')

      window.open(url)
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.file_item {
  margin: 10px 0;
  padding: 5px;
  display: flex;
  justify-content: space-between;
  align-content: center;
  font-size: 14px;
  border-radius: 2px;
  cursor: pointer;
}
.file_item:hover {
  background-color: #e6f7ff;
  color: #40a9ff;
}
.preview:hover {
  cursor: pointer;
  color: #40a9ff;
}
</style>
